<?php
/**
 * Introduction: 支付回调
 * @author: 杨陈鹏
 * @email: yangchenpeng@cdlinglu.com
 */

namespace App\Controller\Pay;


use Think\Alipay\Alipay;
use Think\Controller;
use Think\Exception;
use Think\Wxpay\Wxpay;

class CallbackController extends Controller
{


    /**
     * Introduction: 支付宝APP支付回调
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function alipay()
    {

        $alipay = new Alipay();


        //$datas = I('post.');

        //file_put_contents(APP_PATH.'alipay_callback.log',json_encode($datas));

        //签名验证
//        if ( !$alipay->verifyNotify(true,APP_PATH.'alipay_callback_data.log') )
//             exit ("fail");

        $data = I('post.');
        $order_logic = D('Common/Order','Logic');
        $status = $order_logic::$model->where(['number'=>$data['out_trade_no']])->getField('status');
        if($status == 2)
            exit('success');

        //组装订单信息
        $order_data['pay_type'] = 2;
        $order_data['third_number'] = $data['trade_no'];
        $order_data['third_accounts'] = $data['buyer_email'];
        $order_data['third_use_account'] = $data['buyer_id'];
        $order_data['third_use_account'] = 2;
        $order_data['pay_time'] = NOW_TIME;
        $order_data['status'] = 2;

        $member_consumption['description'] = $data['body'].'(支付宝支付)';
        $member_consumption['time'] = NOW_TIME;
        $member_consumption['nums'] = $data['total_fee'] * 100;

        //商品增加销量和减去库存
        $order_logic::success(['number' => $data['out_trade_no']]);
        //更新余额
        $balance_pay_nums = $order_logic::$model
            ->where( ['number' => $data['out_trade_no']] )
            ->getField('balance_pay_nums');
        $sql =  $order_logic::$model
            ->fetchSql(true)
            ->where( ['number' => $data['out_trade_no']] )
            ->getField('balance_pay_nums');
        try{
            $model = M();
            //开启事物
            $model->startTrans();
            $member_consumption['uid'] = $model
                ->table( '__ORDER__' )
                ->where( ['number' => $data['out_trade_no']] )
                ->getField( 'uid' );
            //修改订单状态
            $res_order = $model
                ->table( '__ORDER__' )
                ->where( ['number' => $data['out_trade_no']] )
                ->save($order_data);
            $res_member_consumption = $model
                ->table('__MEMBER_CONSUMPTION_RECORD__')
                ->add($member_consumption);
            //更新余额

            $update_balance = $model
                            ->table('__MEMBER__')
                            ->where(['uid' => $member_consumption['uid']])
                            ->setDec('balance',$balance_pay_nums);
            //更新冻结直接
            $update_frozen = $model
                ->table('__MEMBER__')
                ->where(['uid' => $member_consumption['uid']])
                ->setDec('frozen',$balance_pay_nums);

            if ( $res_order && $res_member_consumption && $update_balance && $update_frozen ){
                //提交事物
                $model->commit();
                exit ("success");
            }

            //事物回滚
            $model->rollback();
            exit ("fail");

        } catch (\Exception $e){
            file_put_contents(LOG_PATH.'alipay_callback_error_'.$data['out_trade_no'].'.log',$e->getMessage());
        }

    }
    /**
     * Introduction: app微信支付回调
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    public function wxpay()
    {

//$str = '<xml><appid><![CDATA[wxeb7707c46ea2166d]]></appid>
//<attach><![CDATA[20160512071328AHsAfy3ieQD]]></attach>
//<bank_type><![CDATA[CFT]]></bank_type>
//<cash_fee><![CDATA[2]]></cash_fee>
//<fee_type><![CDATA[CNY]]></fee_type>
//<is_subscribe><![CDATA[Y]]></is_subscribe>
//<mch_id><![CDATA[1342308801]]></mch_id>
//<nonce_str><![CDATA[gda0yodnxwvdgqaxjfq224a2yhozpi7w]]></nonce_str>
//<openid><![CDATA[oha7yv1ucRU18nxhs0RYDuklO6S0]]></openid>
//<out_trade_no><![CDATA[87847662996931966286]]></out_trade_no>
//<result_code><![CDATA[SUCCESS]]></result_code>
//<return_code><![CDATA[SUCCESS]]></return_code>
//<sign><![CDATA[56EB06128672574EEF068D625C7B5F31]]></sign>
//<time_end><![CDATA[20160513101735]]></time_end>
//<total_fee>2</total_fee>
//<trade_type><![CDATA[JSAPI]]></trade_type>
//<transaction_id><![CDATA[4002882001201605135795056382]]></transaction_id>
//</xml>';

        $data = file_get_contents("php://input");

        //日志
        //file_put_contents(APP_PATH.'wxpay-callback-'. time() .'.log',$data);

        $pay = new Wxpay();

        $data = $pay->WxPayAppResults($data);
        //$data = $pay->WxPayResults($data);

        //获取支付状态
        $return_code    = $data['return_code'];



        if( $return_code == 'SUCCESS' ){

            //获取订单号
            $number         = $data['attach'];


            $order_logic = D('Common/Order','Logic');
            $status = $order_logic::$model->where(['number'=>$number])->getField('status');

            if($status == 2)
                exit('success');
            //获取支付金额


            //组装订单信息
            $order_data['pay_type'] = 1;
            $order_data['third_number'] = $data['transaction_id'];

            $order_data['pay_time'] = NOW_TIME;
            $order_data['status'] = 2;

            $member_consumption['description'] = '(微信支付)';//$data['body'].'(支付宝支付)';
            $member_consumption['time'] = NOW_TIME;
            $member_consumption['nums'] = $data['total_fee'];

            $order_logic = D('Common/Order','Logic');
            //商品增加销量和减去库存
            $order_logic::success(['number' => $number]);
            //获取订单里面的余额支付金额
            $balance_pay_nums = $order_logic::$model
                ->where( ['number' => $number] )
                ->getField('balance_pay_nums');

            try{
                $model = M();
                //开启事物
                $model->startTrans();
                $member_consumption['uid'] = $model
                    ->table( '__ORDER__' )
                    ->where( ['number' => $number] )
                    ->getField( 'uid' );
                //修改订单状态
                $res_order = $model
                    ->table( '__ORDER__' )
                    ->where( ['number' => $number] )
                    ->save($order_data);
                $res_member_consumption = $model
                    ->table('__MEMBER_CONSUMPTION_RECORD__')
                    ->add($member_consumption);
                //更新余额
                $update_balance = $model
                    ->table('__MEMBER__')
                    ->where(['uid' => $member_consumption['uid']])
                    ->setDec('balance',$balance_pay_nums);
                //更新冻结直接
                $update_frozen = $model
                    ->table('__MEMBER__')
                    ->where(['uid' => $member_consumption['uid']])
                    ->setDec('frozen',$balance_pay_nums);
                if ( $res_order && $res_member_consumption && $update_balance && $update_frozen){
                    //提交事物
                    $model->commit();
                    exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
                }
            }catch (\Exception $e) {
                //事物回滚
                $model->rollback();
                file_put_contents(LOG_PATH.'wxpay_callback_error_'.$number.'.log',$e->getMessage());
                exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[]]></return_msg></xml>');
            }
        }
        //事物回滚
        $model->rollback();
        exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[]]></return_msg></xml>');

    }

}